package model

import (
	"server/share/config"
	"strconv"
	"strings"

	"github.com/hwcer/cosgo/schema"
	"github.com/hwcer/updater"
	"github.com/hwcer/updater/dataset"
	"github.com/hwcer/updater/operator"
)

func init() {
	Register(&Chapter{})
}

type Chapter struct {
	OID    string           `bson:"_id" json:"_id,omitempty"`
	IID    int32            `bson:"iid" json:"id"`
	Uid    string           `bson:"uid" json:"-"  index:"name:_idx_uid_primary" `
	Reward []int32          `bson:"reward" json:"reward"`       //本章奖励领取情况 0 1 2 三个档位
	Stage  map[int32]*Stage `bson:"stageData" json:"stageData"` //本章关卡通关情况
}

type Stage struct {
	Pass  int8             `bson:"pass" json:"pass"`   //是否通过
	Score int32            `bson:"score" json:"score"` //得分
	Data  map[string]int32 `bson:"data" json:"data"`   //通关数据
}

func (this *Chapter) Set(k string, v any) (any, bool) {
	switch k {
	case "reward", "Reward":
		this.Reward = v.([]int32)
	case "stageData", "Stage":
		this.Stage = v.(map[int32]*Stage)
	default:
		arr := strings.Split(k, ".")
		if len(arr) != 2 && arr[0] != "stageData" {
			return nil, false
		}
		key, err := strconv.Atoi(arr[1])
		if err != nil {
			return nil, false
		}
		if this.Stage == nil {
			this.Stage = make(map[int32]*Stage)
		}
		this.Stage[int32(key)] = v.(*Stage)
	}

	return v, true
}

// ----------------- 作为MODEL方法--------------------
func (this *Chapter) Schema() *schema.Schema {
	sch, _ := schema.Parse(this)
	return sch
}

func (this *Chapter) Clone() any {
	r := *this
	return &r
}
func (this *Chapter) IType(iid int32) int32 {
	return config.ITypeChapter
}
func (this *Chapter) Upsert(u *updater.Updater, op *operator.Operator) bool {
	return true
}

func (this *Chapter) Getter(u *updater.Updater, coll *dataset.Collection, keys []string) error {
	tx := db.Omit("uid")
	if len(keys) > 0 {
		tx = tx.Where("_id IN ?", keys)
	}

	var rows []*Chapter
	if tx = tx.Find(&rows); tx.Error != nil {
		return tx.Error
	}
	for _, v := range rows {
		coll.Receive(v.OID, v)
	}
	return nil
}
func (this *Chapter) Setter(u *updater.Updater, bw dataset.BulkWrite) error {
	return bw.Submit()
}

func (this *Chapter) BulkWrite(u *updater.Updater) dataset.BulkWrite {
	bw := NewBulkWrite(this)
	return bw
}
